<script setup lang="ts" name="BpmnDesigner">
import { storeToRefs } from 'pinia'
import { useSettingStore } from '@/store/bpmnProcess/settingStore'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { initModeler } from './initModeler'
import { createNewDiagram } from '../../utils'
import { getModelerOptions } from '../../utils/modelerOptions'
const canvasRef = ref(null)

const emit = defineEmits(['command-stack-changed', 'modeler-init'])

const settingStore = useSettingStore()

const modelerStore = useModelerStore()

const { xml } = storeToRefs(modelerStore)

const newSettings = computed(() => {
  return JSON.stringify(settingStore)
})

watch(
  () => newSettings.value,
  async (value, oldValue) => {
    const valueJson = JSON.parse(value)
    const oldValueJson = oldValue ? JSON.parse(oldValue) : undefined
    try {
      const options = getModelerOptions(valueJson)
      await nextTick()
      await initModeler(canvasRef, options, emit)
      if (xml.value) {
        if (oldValueJson && valueJson.editor.processEngine !== oldValueJson.editor.processEngine) {
          createNewDiagram(valueJson.editor.processEngine)
        } else {
          createNewDiagram(valueJson.editor.processEngine, xml.value)
        }
      } else {
        createNewDiagram(valueJson.editor.processEngine)
      }
    } catch (e) {
      console.log(e)
    }
  },
  {
    immediate: true,
    deep: true
  }
)

onMounted(() => {
  document.body.addEventListener('contextmenu', function (ev) {
    ev.preventDefault()
  })
})
</script>

<template>
  <div class="canvas" ref="canvasRef"></div>
</template>

<style scoped lang="scss">
.canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>
